const Comment = require('../model/comment')


class commentCtl {
  //检查答案是否存在
  async checkcommentExist(ctx, next) {
    const comment = await Comment.findById(ctx.params.id)
    if(!comment) {
      ctx.throw(404, "评论不存在")
    }
    if( ctx.params.questionId && comment.questionId !== ctx.params.questionId) {
      ctx.throw(404, "该问题下此答案不存在")
    }
    if( ctx.params.answerId && comment.answerId !== ctx.params.answerId) {
      ctx.throw(404, "该答案下此评论不存在")
    }
    ctx.state.comment = comment
    await next()
  }
  //检查问题拥有着

  async checkcommentator (ctx, next) {
    const { comment } = ctx.state
    if(comment.commentator.toString() !== ctx.state.user._id) {
      ctx.throw(403,'没有权限')
    }
    await next()
  }




  async find(ctx) {
    const { per_page = 3, page = 1 } = ctx.query
    const perpage = Math.max(per_page * 1, 1)
    const pages = Math.max(page * 1, 1) - 1
    const q = new RegExp(ctx.query.q)
    const { rootCommentId } = ctx.query
    const { questionId, answerId } = ctx.params
    // $or: [{ content: q }, { description: q }]
    ctx.body = await Comment.find({ content: q, questionId, answerId, rootCommentId }).limit(perpage).skip(pages * perpage).populate('commentator replyTo')
  }
  async findById(ctx) {
    const { fields = '' } = ctx.query
    const selectField = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    const comment = await Comment.findById(ctx.params.id).select(selectField).populate('commentator')
    ctx.body = comment
  }
  async create(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: true },
      rootCommentId: { type: 'string', required: false },
      replyTO: { type: 'string', required: false },
    })
    const comment = await new Comment({...ctx.request.body, commentator: ctx.state.user._id, questionId: ctx.params.questionId, answerId: ctx.params.answerId}).save()
    ctx.body = comment
  }

  async update(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: false },
    })
    const { content } = ctx.request.body
    await ctx.state.comment.update({ content })
    ctx.body = ctx.state.comment
       
     
  }
  async del(ctx) {
    await Comment.findByIdAndRemove(ctx.params.id)
    ctx.status = 204
  }

}
module.exports = new commentCtl()